package com.sgu6.sgu6_machine.ui.fragment;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.sgu6.middleware.event.WarningEvent;
import com.sgu6.middleware.manager.ThreadManager;
import com.sgu6.middleware.util.HexUtil;
import com.sgu6.serialport.manager.SerialPortManagerForCard;
import com.sgu6.sgu6_machine.R;
import com.sgu6.sgu6_machine.base.BaseF;
import com.sgu6.sgu6_machine.common.Constant;
import com.sgu6.sgu6_machine.config.MachineConfig;
import com.sgu6.sgu6_machine.container.ComContainer;
import com.sgu6.sgu6_machine.container.MachineContainer;
import com.sgu6.sgu6_machine.dto.GoodsSimpleDto;
import com.sgu6.sgu6_machine.dto.MemberCardInfoDto;
import com.sgu6.sgu6_machine.event.ReadCardEvent;
import com.sgu6.sgu6_machine.event.SelectBuyNoEvent;
import com.sgu6.sgu6_machine.event.SelectTypeEvent;
import com.sgu6.sgu6_machine.presenter.MachineP;
import com.sgu6.sgu6_machine.service.ReadCardS;
import com.sgu6.sgu6_machine.ui.fragment.buy.PayCodeF;
import com.sgu6.sgu6_machine.ui.fragment.buy.ReadCardF;
import com.sgu6.sgu6_machine.ui.fragment.buy.SwipeCardF;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class BuyF extends BaseF implements View.OnTouchListener {


    @BindView(R.id.btn1)
    LinearLayout btn1;
    @BindView(R.id.btn2)
    LinearLayout btn2;
    @BindView(R.id.btn3)
    LinearLayout btn3;
    @BindView(R.id.btn4)
    LinearLayout btn4;
    @BindView(R.id.btn5)
    LinearLayout btn5;
    @BindView(R.id.btn6)
    LinearLayout btn6;
    @BindView(R.id.btn7)
    LinearLayout btn7;


    @BindView(R.id.ll_rice)
    LinearLayout llRice;
    @BindView(R.id.ll_water)
    LinearLayout llWater;
    @BindView(R.id.buy_container)
    FrameLayout buyContainer;
    @BindView(R.id.container)
    LinearLayout container;
    private Fragment payCodeF, readCardF;
    private FragmentManager fm;
    private FragmentTransaction ft;

    private GoodsSimpleDto goodsSimpleDto;
    private Timer timer = new Timer();
    private Timer cardInfoTimer = new Timer();
    private boolean pageClick = false;
    private MachineP machineP = new MachineP();
    private MediaPlayer player;
    private ReadCardS readCardS;
    private boolean isReadCard = true;
    private ServiceConnection conn;
    private int buyNo = 1;
    private String sgu6_code;

    public static BuyF newInstance(String params) {
        return new BuyF();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_buy, container, false);
        unbinder = ButterKnife.bind(this, v);
        fm = getChildFragmentManager();
        initFragments();

        conn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                ReadCardS.MachineBinder myBinder = (ReadCardS.MachineBinder) service;
                readCardS = myBinder.getService();
                Log.i(TAG, "onServiceConnected: ");
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };

        requireContext().bindService(new Intent(requireContext(), ReadCardS.class), conn, Context.BIND_AUTO_CREATE);
        container.setOnTouchListener(this);


        return v;
    }


    public void play(int id) {
        ThreadManager.getThreadPollProxy().execute(() -> {
            if (player != null && player.isPlaying()) {
                player.pause();
                player.reset();
            }
            try {
                player = MediaPlayer.create(requireContext(), id);
                player.start();//开始或恢复播放
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }


    private void initFragments() {
        payCodeF = PayCodeF.newInstance("");
        readCardF = ReadCardF.newInstance("");

        ft = fm.beginTransaction();
        ft.add(R.id.buy_container, payCodeF, "");
        ft.add(R.id.buy_container, readCardF, "");

        ft.hide(readCardF);
        ft.commitAllowingStateLoss();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            buyNo = 1;
            select1();
            stopTimer();
            stopCardInfoTimer();
        } else {
            showPayCodeFragment();
            buyNo = 1;
            if (MachineContainer.categoryId.equals(Constant.CAO_MI)) {
                play(R.raw.baidu_select_cao);
            } else if (MachineContainer.categoryId.equals(Constant.PEI_MI)) {
                play(R.raw.baidu_select_pei);
            } else {
                play(R.raw.baidu_select_jing);
            }
            startTimer();
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        requireContext().unbindService(conn);
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReadCardEvent(ReadCardEvent event) {
        if (event.cmd.startsWith("AA120400") && MachineContainer.isConsumption) {
            play(R.raw.baidu_shuaka_finish);
            sgu6_code = event.cmd.substring(8);
            machineP.getMemberCardInfo(sgu6_code);
            stopTimer();
//            showReadCardFragment();
            if (MachineContainer.isConsumption) {
                showReadCardFragment();
            }
            SerialPortManagerForCard.getInstance().sendBytes(HexUtil.HexString2Bytes("AA03B20501"));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMemberCardInfoEvent(MemberCardInfoDto memberCardInfoDto) {
        stopCardInfoTimer();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSelectTypeEvent(SelectTypeEvent event) {
        goodsSimpleDto = event.goodsSimpleDto;
        //更新斤数
        if (event.goodsSimpleDto.getCategoryId().equals(Constant.WATER)){
            buyNo = 5;
            llWater.setVisibility(View.VISIBLE);
            llRice.setVisibility(View.GONE);
        }else {
            llWater.setVisibility(View.GONE);
            llRice.setVisibility(View.VISIBLE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWarningEvent(WarningEvent event) {
        pageClick = event.showWarning;
    }


    private void startTimer() {
        if (!isReadCard) {
            isReadCard = true;
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (MachineContainer.machineConfigDto.merchantId != null && MachineContainer.machineConfigDto.merchantId.length() > 12) {
                        String key = MachineContainer.machineConfigDto.merchantId.substring(0, 12);
                        SerialPortManagerForCard.getInstance().sendBytes(HexUtil.HexString2Bytes("AA080400FFFFFFFFFFFF"));
                    }else {
                        System.out.println(111);
                    }
                }
            }, Constant.READ_CARD_DELAY, Constant.READ_CARD_PERIOD);
        }
    }

    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
            isReadCard = false;
        }
    }

    private void stopCardInfoTimer() {
        if (cardInfoTimer != null) {
            cardInfoTimer.cancel();
            isReadCard = false;
        }
    }

    private void showPayTypeFragment() {
        ft = fm.beginTransaction();
        ft.show(payCodeF);
        ft.hide(readCardF);
        ft.commitAllowingStateLoss();
    }

    private void showPayCodeFragment() {
        ft = fm.beginTransaction();
        ft.show(payCodeF);
        ft.hide(readCardF);
        ft.commitAllowingStateLoss();
    }

    private void showReadCardFragment() {
        ft = fm.beginTransaction();
        ft.show(readCardF);
        ft.hide(payCodeF);
        ft.commitAllowingStateLoss();
    }


    private void select1() {
        btn1.setBackgroundResource(R.drawable.shape_buy_no_select);

        btn2.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn3.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn4.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn5.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn6.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        buyNo = 1;
    }

    private void select2() {
        btn1.setBackgroundResource(R.drawable.shape_buy_no_unselect);

        btn2.setBackgroundResource(R.drawable.shape_buy_no_select);
        btn3.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn4.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn5.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn6.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        buyNo = 2;
    }

    private void select3() {
        btn1.setBackgroundResource(R.drawable.shape_buy_no_unselect);

        btn2.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn3.setBackgroundResource(R.drawable.shape_buy_no_select);
        btn4.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn5.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn6.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        buyNo = 3;
    }

    private void select4() {
        btn1.setBackgroundResource(R.drawable.shape_buy_no_unselect);

        btn2.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn3.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn4.setBackgroundResource(R.drawable.shape_buy_no_select);
        btn5.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn6.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        buyNo = 4;
    }

    private void select5() {
        btn1.setBackgroundResource(R.drawable.shape_buy_no_unselect);

        btn2.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn3.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn4.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn5.setBackgroundResource(R.drawable.shape_buy_no_select);
        btn6.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        buyNo = 5;
    }

    private void select6() {
        btn1.setBackgroundResource(R.drawable.shape_buy_no_unselect);

        btn2.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn3.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn4.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn5.setBackgroundResource(R.drawable.shape_buy_no_unselect);
        btn6.setBackgroundResource(R.drawable.shape_buy_no_select);
        buyNo = 6;
    }

    private void select7() {
        buyNo = 5;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return pageClick;
    }


    @OnClick({R.id.btn1, R.id.btn2, R.id.btn3, R.id.btn4, R.id.btn5, R.id.btn6,R.id.btn7})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn1:
                play(R.raw.baidu1);
                select1();
                EventBus.getDefault().post(new SelectBuyNoEvent(1));
                break;
            case R.id.btn2:
                play(R.raw.baidu2);
                select2();
                EventBus.getDefault().post(new SelectBuyNoEvent(2));
                break;
            case R.id.btn3:
                play(R.raw.baidu3);
                select3();
                EventBus.getDefault().post(new SelectBuyNoEvent(3));
                break;
            case R.id.btn4:
                play(R.raw.baidu4);
                select4();
                EventBus.getDefault().post(new SelectBuyNoEvent(4));
                break;
            case R.id.btn5:
                play(R.raw.baidu5);
                select5();
                EventBus.getDefault().post(new SelectBuyNoEvent(5));
                break;
            case R.id.btn6:
                play(R.raw.baidu6);
                select6();
                EventBus.getDefault().post(new SelectBuyNoEvent(6));
                break;
            case R.id.btn7:
//                play(R.raw.baidu7);
                select7();
                EventBus.getDefault().post(new SelectBuyNoEvent(5));
                break;
        }
    }
}
